<template>
  <div class="app-container">
    <!-- 待提现金额 -->
    <div class="withdraw-amount-info">
      <span class="amount-label">待提现金额：</span>
      <span class="amount-value">￥{{ withdrawAmount }}</span>
      <el-button 
        type="primary" 
        size="default"
        :disabled="withdrawAmount <= 0"
        @click="handleApplyWithdraw"
        style="margin-left: 20px;"
      >
        申请提现
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item>
            <el-select 
              v-model="queryParams.auditStatus" 
              placeholder="审核状态" 
              clearable 
              style="width: 100%"
            >
              <el-option label="待审核" value="0" />
              <el-option label="审核通过" value="1" />
              <el-option label="审核拒绝" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleQuery">查 询</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 提现记录表格 -->
    <el-table 
      :data="withdrawList" 
      v-loading="loading" 
      border
      style="margin-top: 20px"
    >
      <el-table-column label="提现标题" prop="title" min-width="200" />
      <el-table-column label="提现金额" prop="amount" min-width="120">
        <template #default="{ row }">
          <span class="text-success">￥{{ row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="银行名称" prop="bankAccount" min-width="120" />
      <el-table-column label="银行账号" prop="bankName" min-width="180" />
      <el-table-column label="账户持有人" prop="accountHolder" min-width="100" />
      <el-table-column label="审核状态" prop="auditStatus" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getAuditStatusType(row.auditStatus)">
            {{ getAuditStatusText(row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" prop="applyTime" min-width="160" />
      <el-table-column label="审核时间" prop="auditTime" min-width="160">
        <template #default="{ row }">
          {{ row.auditTime || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="审核备注" prop="auditRemark" min-width="120">
        <template #default="{ row }">
          {{ row.auditRemark || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="打款状态" prop="paymentStatus" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getPaymentStatusType(row.paymentStatus)">
            {{ getPaymentStatusText(row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button 
            link 
            type="primary" 
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-show="total > 0"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="val => { queryParams.pageSize = val; getWithdrawList() }"
        @current-change="val => { queryParams.pageNum = val; getWithdrawList() }"
      />
    </div>

    <!-- 提现申请弹窗 -->
    <WithdrawDl 
      v-model:visible="withdrawVisible" 
      :amount="withdrawAmount" 
      @submit="handleWithdrawSubmit" 
      @cancel="withdrawVisible = false"
    />

    <!-- 提现详情弹窗 -->
    <WithdrawDetailDl 
      v-model:visible="detailVisible" 
      :withdraw-info="currentWithdrawInfo" 
    />
  </div>
</template>

<script setup name="WithdrawManagement">
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue'
import billApi from '@/api/room/bill'
import { getWithdrawList as fetchWithdrawList } from '@/api/payment/withdraw'
import useUserStore from '@/store/modules/user'
import WithdrawDl from '@/components/WithdrawDl/index.vue'
import WithdrawDetailDl from '@/components/WithdrawDetailDl/index.vue'

const { proxy } = getCurrentInstance()

const loading = ref(false)
const total = ref(0)
const withdrawAmount = ref(0)
const withdrawVisible = ref(false)
const detailVisible = ref(false)
const withdrawList = ref([])
const dateRange = ref([])
const currentWithdrawInfo = ref({})

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    auditStatus: '',
    beginTime: '',
    endTime: ''
  }
})

const { queryParams } = toRefs(data)

// 获取待提现金额
function getWithdrawAmount() {
  const userStore = useUserStore()
  const apartmentId = userStore.apartment.apartmentId
  
  if (!apartmentId) {
    console.error('未获取到公寓ID')
    return
  }
  
  billApi.getUnwithdrawAmount(apartmentId).then(res => {
    if (res.code === 200) {
      withdrawAmount.value = res.data || 0
    }
  }).catch(err => {
    console.error('获取待提现金额失败', err)
    withdrawAmount.value = 0
  })
}

// 获取提现记录列表
function getWithdrawList() {
  loading.value = true
  fetchWithdrawList(queryParams.value).then(res => {
    if (res.code === 200) {
      withdrawList.value = res.rows || []
      total.value = res.total || 0
    }
  }).catch(err => {
    console.error('获取提现记录失败', err)
    withdrawList.value = []
    total.value = 0
  }).finally(() => {
    loading.value = false
  })
}

// 处理日期变化
function handleDateChange(val) {
  if (val) {
    queryParams.value.beginTime = val[0]
    queryParams.value.endTime = val[1]
  } else {
    queryParams.value.beginTime = ''
    queryParams.value.endTime = ''
  }
}

// 查询
function handleQuery() {
  queryParams.value.pageNum = 1
  getWithdrawList()
}

// 申请提现
function handleApplyWithdraw() {
  if (withdrawAmount.value <= 0) {
    proxy.$modal.msgInfo('暂无可提现金额')
    return
  }
  withdrawVisible.value = true
}

// 提现提交成功回调
function handleWithdrawSubmit() {
  // 刷新数据
  getWithdrawAmount()
  getWithdrawList()
}

// 查看详情
function handleViewDetail(row) {
  currentWithdrawInfo.value = { ...row }
  detailVisible.value = true
}

// 获取审核状态类型
function getAuditStatusType(status) {
  const statusMap = {
    '0': 'warning',
    '1': 'success',
    '2': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取审核状态文本
function getAuditStatusText(status) {
  const statusMap = {
    '0': '待审核',
    '1': '审核通过',
    '2': '审核拒绝'
  }
  return statusMap[status] || '--'
}

// 获取打款状态类型
function getPaymentStatusType(status) {
  const statusMap = {
    '0': 'warning',
    '1': 'success',
    '2': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取打款状态文本
function getPaymentStatusText(status) {
  const statusMap = {
    '0': '待打款',
    '1': '已打款',
    '2': '打款失败'
  }
  return statusMap[status] || '--'
}

onMounted(() => {
  getWithdrawAmount()
  getWithdrawList()
})
</script>

<style lang="scss" scoped>
.withdraw-amount-info {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
  
  .amount-label {
    font-size: 16px;
    color: #606266;
  }
  
  .amount-value {
    font-size: 20px;
    font-weight: bold;
    color: #409eff;
  }
}

.text-success {
  color: var(--el-color-success);
}

.search-form {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style> 